package com.dianshang.springdataredis;

import com.dianshang.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import redis.clients.jedis.Jedis;

import java.util.Set;

/**
 * Set类型(无序不可重复)
 */
@RunWith(SpringJUnit4ClassRunner.class) // Spring整合Redis的核心类
@ContextConfiguration(locations = "classpath:applicationContext-redis.xml") // 上下文配置文件
public class SetDemo {

    @Autowired
    private RedisTemplate redisTemplate;

    // 添加
    @Test
    public void add(){
        User user1 = new User(1,"张三","123");
        User user2 = new User(2,"李四","456");
        User user3 = new User(3,"王五","789");
        redisTemplate.boundSetOps("user").add(user1);
        redisTemplate.boundSetOps("user").add(user2);
        redisTemplate.boundSetOps("user").add(user3);
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.sadd("user", "{id:4,username:'赵六',password:'111213'}");
    }

    // 查询所有
    @Test
    public void findAll(){
        Set<User> users = redisTemplate.boundSetOps("user").members();
        for (User user : users) {
            System.out.println(user);
        }
    }

    // 根据条件删除
    @Test
    public void delete(){
        User user1 = new User(1,"张三","123");
        redisTemplate.boundSetOps("user").remove(user1);
        // 物理删除所有
        // redisTemplate.delete("user");
    }

}